﻿using System.Configuration;
using System.Data.Entity;
using System.Data.SqlClient;

namespace Yz.Base.Dal
{
    public static class DbContextExtension
    {
        /// <summary>
        /// 将EF DbContext一些跟踪特性关闭，提高性能(只读数据库时使用)
        /// </summary>
        /// <param name="dbContext"></param>
        public static void SetDbReadOnly(this DbContext dbContext)
        {
            //是否通过 DbContext 和相关类的方法自动调用 DetectChanges 方法。
            dbContext.Configuration.AutoDetectChangesEnabled = false;
            //在调用 SaveChanges 时，是否应自动验证所跟踪的实体
            dbContext.Configuration.ValidateOnSaveEnabled = false;
            //是否会创建动态生成的代理类的实例，如果为false，延迟加载失效
            dbContext.Configuration.ProxyCreationEnabled = false;
            //是否启用针对公开为导航属性的关系的延迟加载
            dbContext.Configuration.LazyLoadingEnabled = false;
            ///比较两个操作数，而它们都可能为 null 时，是否展示数据库 null 语义
            ///例如：如果 UseDatabaseNullSemantics 为 true，则 (operand1 == operand2) 将转换为 (operand1 = operand2)；
            ///如果 UseDatabaseNullSemantics 为 false，则将转换为 (((operand1 = operand2) AND (NOT (operand1 IS NULL OR operand2 IS NULL))) OR ((operand1 IS NULL) AND (operand2 IS NULL)))。
            dbContext.Configuration.UseDatabaseNullSemantics = true;
        }

        /// <summary>
        /// 获取数据库访问权限（返回false时为只读）
        /// </summary>
        /// <param name="connStrName"></param>
        /// <returns>返回为ture时有读写权限，否则为只读权限</returns>
        public static bool GetDbPrivilege(string connStrName)
        {
            bool readWrite = true;
            string connStr = ConfigurationManager.ConnectionStrings[connStrName].ConnectionString;
            SqlConnectionStringBuilder sqlsb = new SqlConnectionStringBuilder(connStr);
            if (sqlsb.ApplicationIntent == ApplicationIntent.ReadOnly)
            {
                readWrite = false;
            }
            return readWrite;
        }
    }
}
